"""
URL configuration for iClouds project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

from django.conf import settings
from django.contrib import admin
from django.urls import path, include

DESCRIPTION = """
    携带版本号:  ?version=1 
    所有接口文档。包括以下应用：
    1 admin: 后台管理员接口.
"""

urlpatterns = [
    # path('admin/', admin.site.urls),
    path(
        "api/",
        include(("mysqldb.urls", "mysqldb"), namespace="mysqldb"),
        name="全局接口",
    ),
    path(
        "admin/",
        include(("Admin.urls", "Admin"), namespace="Admin"),
        name="管理员接口",
    ),
    # path(
    #     "staff/",
    #     include(("Staff.urls", "Staff"), namespace="Staff"),
    #     name="员工接口",
    # ),
    # path(
    #     "main/",
    #     include(("Main.urls", "Main"), namespace="Main"),
    #     name="公司主体接口",
    # ),
    # path(
    #     "match/",
    #     include(("Aatchs.urls", "Aatchs"), namespace="Aatchs"),
    #     name="赛事接口",
    # ),
]

from .allRoute import get_all_url_dict
from rest_framework.compat import coreapi
from rest_framework.schemas.coreapi import SchemaGenerator, distribute_links


class CustomSchemaGenerator(SchemaGenerator):
    keys = get_all_url_dict(urlpatterns)

    def get_schema(self, request=None, public=False):
        self._initialise_endpoints()
        links = self.get_links(None if public else request)
        if not links:
            return None

        url = self.url
        if not url and request is not None:
            url = request.build_absolute_uri()

        distribute_links(links)
        links = dict(links)
        sess = links.copy()
        for k, v in sess.items():
            v = dict(v)
            for ck, cv in v.items():
                if self.keys.get(f"/{k}/{ck}/"):
                    links[k].update({self.keys.get(f"/{k}/{ck}/"): links[k].pop(ck)})
                else:
                    links[k].update({ck: links[k].pop(ck)})
        # print(links)
        return coreapi.Document(
            title=self.title, description=self.description, url=url, content=links
        )


if settings.DEBUG:
    from rest_framework.documentation import include_docs_urls

    schema_view = include_docs_urls(
        title="iClouds", description=DESCRIPTION, generator_class=CustomSchemaGenerator
    )
    urlpatterns.append(
        # 文档页面
        path("docs/", schema_view, name="接口文档"),
    )
